/**
 * User: Obi
 * Date: 02.08.11
 * Time: 20:03
 */
package com.jediflasher.game_client.data.world {
	import com.jediflasher.game_client.data.BaseData;
	import com.jediflasher.game_client.data.UniverseData;
	import com.jediflasher.game_client.events.model.WorldDataEvent;
	import com.jediflasher.game_client.server.messages.ChangeUsers;
	import com.jediflasher.game_client.server.messages.CharacterInfoResponse;
	import com.jediflasher.game_client.server.messages.WorldInfoResponse;
	import com.netease.protobuf.Message;

	[Event(name="characterAdded", type="com.jediflasher.game_client.events.model.WorldDataEvent")]
	public class WorldData extends BaseData {

		public function WorldData(universe:UniverseData) {
			super(universe);
		}

		/**
		 * @private
		 */
		private var _charactersList:Vector.<CharacterData> = new Vector.<CharacterData>();

		public function get charactersList():Vector.<CharacterData> {
			return this._charactersList;
		}

		/**
		 * @private
		 */
		private var _charactersHash:Object = new Object();

		public override function read(message:Message):void {
			if (message is CharacterInfoResponse) {
				this.readCharacterInfo(message as CharacterInfoResponse)
			}
			else if (message is WorldInfoResponse) {
				this.readWorldInfo(message as WorldInfoResponse)
			}
			else if (message is ChangeUsers) {
				this.readChangeUsers(message as ChangeUsers);
			}
		}

		public function addCharacter(character:CharacterData):void {
			var charId:int = character.id;

			if (hasCharacter(charId)) {
				super.logError("Character already added!");
				return;
			}

			this._charactersList.push(character);
			this._charactersHash[charId] = character;
			super.dispatchEvent(new WorldDataEvent(WorldDataEvent.CHARACTER_ADDED, character));
		}

		public function getCharacterById(characterId:int):CharacterData {
			return this._charactersHash[characterId] as CharacterData;
		}

		public function hasCharacter(id:int):Boolean {
			return id in _charactersHash;
		}

		private function readCharacterInfo(info:CharacterInfoResponse):void {
			var targetUser:CharacterData = this.getCharacterById(info.characterId);

			// пришли мы сами, можно даже себя создать самому
			if (!targetUser && this.userId == info.characterId) {
				targetUser = new CharacterData(this.universe, this.userId);
				targetUser.read(info);
				this.addCharacter(targetUser);
			}

			if (targetUser) targetUser.read(info);
		}

		private function readWorldInfo(info:WorldInfoResponse):void {

		}

		private function readChangeUsers(info:ChangeUsers):void {
			var len:int = info.users.length;
			for(var i:int = 0; i < len; i++) {
				var userId:int = info.users[i];
				var character:CharacterData = new CharacterData(this.universe, userId);
				this.addCharacter(character);
			}
		}
	}
}
